package src.main.其他模式.服务定位器模式;

import java.util.ArrayList;
import java.util.List;

public class ServiceLocatorPatternDemo {
    public static void main(String[] args) {
        Service service = ServiceLocator.getService("服务1");
        service.execute();
        service = ServiceLocator.getService("服务2");
        service.execute();
        service = ServiceLocator.getService("服务1");
        service.execute();
        service = ServiceLocator.getService("服务2");
        service.execute();
    }
}
/**创建服务接口 Service*/
interface Service {
    String getName();
    void execute();
}

class Service1 implements Service {
    public void execute(){System.out.println("正在执行服务1");}
    @Override
    public String getName() {return "服务1";}
}

class Service2 implements Service {
    public void execute(){System.out.println("正在执行服务2");}
    @Override
    public String getName() {return "服务2";}
}
/** 为JNDI查询创建 InitialContext*/
class InitialContext {
    public Object lookup(String jndiName){
        if(jndiName.equalsIgnoreCase("服务1")){
            System.out.println("查找并创建新的服务1对象");
            return new Service1();
        }else if (jndiName.equalsIgnoreCase("服务2")){
            System.out.println("查找并创建新的服务2对象");
            return new Service2();
        }
        return null;
    }
}

/**创建缓存 Cache*/
class Cache {
    private List<Service> services;
    public Cache(){
        services = new ArrayList<Service>();
    }
    public Service getService(String serviceName){
        for (Service service : services) {
            if(service.getName().equalsIgnoreCase(serviceName)){
                System.out.println("正在返回缓存  "+serviceName+" object");
                return service;
            }
        }
        return null;
    }

    public void addService(Service newService){
        boolean exists = false;
        for (Service service : services) {
            if(service.getName().equalsIgnoreCase(newService.getName())){
                exists = true;
            }
        }
        if(!exists){
            services.add(newService);
        }
    }
}
/**创建服务定位器*/
class ServiceLocator {
    private static Cache cache;
    static {
        cache = new Cache();
    }
    public static Service getService(String jndiName){
        Service service = cache.getService(jndiName);
        if(service != null){
            return service;
        }
        InitialContext context = new InitialContext();
        Service service1 = (Service)context.lookup(jndiName);
        cache.addService(service1);
        return service1;
    }
}